package com.hc.apt;

import com.google.auto.service.AutoService;
import com.hc.annotations.BindView;

import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Filer;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeMirror;
import javax.tools.Diagnostic;
import javax.tools.JavaFileObject;

@AutoService(Processor.class)
public class APTBindView extends AbstractProcessor {
    Filer filer;

    @Override
    public synchronized void init(ProcessingEnvironment processingEnv) {
        super.init(processingEnv);
        processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "---APTBindView---init---");
        filer = processingEnv.getFiler();
    }

    @Override
    public SourceVersion getSupportedSourceVersion() {
        return SourceVersion.latestSupported();
    }

    @Override
    public Set<String> getSupportedAnnotationTypes() {
        Set<String> set = new HashSet<>();
        set.add(BindView.class.getCanonicalName());
        return set;
    }

    @Override
    public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
        if(set.isEmpty()){
            return false;
        }
        //包含 TypeElement类 ExecutableElement方法 VariableElement属性
        Set<? extends Element> elementsAnnotatedWith = roundEnvironment.getElementsAnnotatedWith(BindView.class);
        //以Activity名存放属性集合
        Map<String, List<VariableElement>> map = new HashMap<>();
        for (Element element : elementsAnnotatedWith) {
            if (element instanceof VariableElement) {
                VariableElement variableElement = (VariableElement) element;
                String activityName = variableElement.getEnclosingElement().getSimpleName().toString();
                List<VariableElement> variableElements = map.get(activityName);
                if (variableElements == null) {
                    variableElements = new ArrayList<>();
                    map.put(activityName, variableElements);
                }
                variableElements.add(variableElement);
            }
        }
        //开始生成文件
        if (!map.isEmpty()) {
            Writer writer = null;
            Iterator<String> iterator = map.keySet().iterator();
            while (iterator.hasNext()) {
                String activityName = iterator.next();//获取Activity名
                List<VariableElement> variableElements = map.get(activityName);
                TypeElement enclosingElement = (TypeElement) variableElements.get(0).getEnclosingElement();
                String packageName = processingEnv.getElementUtils().getPackageOf(enclosingElement).toString();//获取Activity所在包名
                try {
                    //com.hc.summary.activity.MainActivity_BindViews
                    //package com.hc.summary.activity;
                    //import com.hc.summary.annotation.IBindView;
                    //public class MainActivity_BindViews implements IBindView<com.hc.summary.activity.MainActivity>{
                    // @Override
                    // public void bind(com.hc.summary.activity.MainActivity target){
                    //  target.textview=(androdi.widget.TextView)target.findViewById(100000);
                    // }
                    //}
                    JavaFileObject sourceFile = filer.createSourceFile(packageName + "." + activityName + "_BindViews");
                    writer = sourceFile.openWriter();
                    writer.write("package " + packageName + ";\n");
                    writer.write("import com.hc.summary.annotation.IBindView;\n");
                    writer.write("public class " + activityName + "_BindViews implements IBindView<" + packageName + "." + activityName + ">{\n");
                    writer.write(" @Override\n");
                    writer.write(" public void bind(" + packageName + "." + activityName + " target){\n");
                    for (VariableElement variableElement : variableElements) {
                        String variableName = variableElement.getSimpleName().toString();//属性名
                        int id = variableElement.getAnnotation(BindView.class).value();
                        TypeMirror typeMirror = variableElement.asType();//属性类型
                        writer.write("  target." + variableName + "=(" + typeMirror + ")target.findViewById(" + id + ");\n");
                    }
                    writer.write(" }\n");
                    writer.write("}\n");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (writer != null) {
                        try {
                            writer.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        //是否传递注解给下个注解处理器 true:否 false是
        return false;
    }
}